#include "circularqueue.hpp"
#include <unistd.h>
#include <pthread.h>
#include <ctime>

void *consumer(void *args)
{
    circularQ<Task> *cq = static_cast<circularQ<Task> *>(args);
    while (true)
    {
        // int data = 0;
        Task t;
        // 1. 消费
        cq->dequeue(&t);

        t();

        // 2. 处理数据
        std::cout << "consumer -> " << t.result() << std::endl;
    }
    
}

void *productor(void *args)
{
    circularQ<Task> *cq = static_cast<circularQ<Task> *>(args);
    while (true)
    {
        sleep(1);
        // int data = rand() % 10 + 1;
        // cq->enqueue(data);

        int x = rand() % 10 + 1;
        usleep(10000 * x);
        int y = rand() % 10 + 1;
        Task t(x, y);
        cq->enqueue(t);

        std::cout << "productor -> " << t.debug() << std::endl;
    }
    
    
}

int main()
{
    srand(time(nullptr) ^ getpid());
    circularQ<Task> *cq = new circularQ<Task>(5);

    // 单生产，单消费
    pthread_t c1, c2, p1, p2, p3;
    pthread_create(&c1, nullptr, consumer, cq);
    pthread_create(&c2, nullptr, consumer, cq);
    pthread_create(&p1, nullptr, productor, cq);
    pthread_create(&p2, nullptr, productor, cq);
    pthread_create(&p3, nullptr, productor, cq);

    pthread_join(c1, nullptr);
    pthread_join(c2, nullptr);
    pthread_join(p1, nullptr);
    pthread_join(p2, nullptr);
    pthread_join(p3, nullptr);

    return 0;
}